package io.gitee.lglbc.easy.security.core.token;

import com.alibaba.fastjson2.JSON;
import io.gitee.lglbc.easy.security.core.config.EasyTokenProperties;
import io.gitee.lglbc.easy.security.core.util.JwtTokenUtil;
import com.nimbusds.jose.jwk.RSAKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * @author Neil Yang
 */
@Service
@EnableConfigurationProperties(EasyTokenProperties.class)
public class TokenService {
    @Autowired
    private EasyTokenProperties easyTokenProperties;

    public String generateToken(EasyPayload easyPayload) {
        Date now = new Date();
        Date exp = new Date(now.getTime() + easyTokenProperties.getExpireTime() * 1000);
        easyPayload.setSub(easyPayload.getUsername());
        easyPayload.setIat(now.getTime());
        easyPayload.setExp(exp.getTime());
        easyPayload.setJti(UUID.randomUUID().toString());
        String payloadStr = JSON.toJSONString(easyPayload);
        if (easyTokenProperties.isEnableRSA()) {
            RSAKey rsaKey = JwtTokenUtil.getRSAKey(easyTokenProperties.getJksName(), easyTokenProperties.getJksSecret());
            return JwtTokenUtil.generateTokenByRSA(payloadStr, rsaKey);
        }
        return JwtTokenUtil.generateTokenByHMAC(payloadStr, easyTokenProperties.getSecret());
    }

    public EasyPayload checkToken(String token) {
        if (easyTokenProperties.isEnableRSA()) {
            RSAKey rsaKey = JwtTokenUtil.getRSAKey(easyTokenProperties.getJksName(), easyTokenProperties.getJksSecret());
            return JwtTokenUtil.checkTokenByRSA(token, rsaKey);
        }
        return JwtTokenUtil.checkTokenByHMAC(token, easyTokenProperties.getSecret());
    }
}
